package com.jung.net

import android.util.ArrayMap
import com.beyond.common.util.AppUtils
import com.beyond.common.util.LogUtils
import com.google.gson.GsonBuilder
import com.jung.net.interceptor.CacheInterceptor
import com.jung.net.interceptor.HeaderInterceptor
import com.jung.net.interceptor.MultiBaseUrlInterceptor
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * @author chenshiyang
 * @time 2022/6/23 17:48
 * @name ServiceCreators.kt
 * @class describe
 */
object ServiceCreators {
    //设置 请求的缓存的大小跟位置
    private val cacheFile = File(AppUtils.instance.cacheDir, "cache_retrofit")
    private val cache = Cache(cacheFile, 1024 * 1024 * 10L)

    private val httpClient = OkHttpClient.Builder().apply {
        addInterceptor(MultiBaseUrlInterceptor())
        addInterceptor(HeaderInterceptor())
        cache(cache)
        addNetworkInterceptor(CacheInterceptor())
        if (!AppUtils.isRelease) {
            addInterceptor(loggerInterceptor())
        }
        NetConstantKeys.CustomerInterceptors.forEach {
            addInterceptor(it)
        }
        //超时时间 连接、读、写
        connectTimeout(NetConstantKeys.CONNECT_TIMEOUT, TimeUnit.SECONDS)
        readTimeout(NetConstantKeys.READ_TIMEOUT, TimeUnit.SECONDS)
        writeTimeout(NetConstantKeys.WRITE_TIMEOUT, TimeUnit.SECONDS)
    }.build()

    private fun getRetrofit(baseUrl: String): Retrofit {
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(httpClient)
            .addConverterFactory(
                GsonConverterFactory.create(
                    GsonBuilder().registerTypeAdapterFactory(
                        GsonTypeAdapterFactory()
                    ).create()
                )
            ).build()
    }

    private val mApis = ArrayMap<String, Any>()

    //对外提供的方法
    @Suppress("UNCHECKED_CAST")
    fun <T> provide(apiInterfaceClass: Class<T>, baseUrl: String?): T {
        val api = mApis[apiInterfaceClass.name] as T ?: getRetrofit(
            baseUrl ?: NetConstantKeys.APP_BASE_URL
        ).create(apiInterfaceClass)
        mApis[apiInterfaceClass.name] = api
        return api
    }

    fun <T> getApi(serviceClass: Class<T>, baseUrl: String): T = Retrofit.Builder()
        .baseUrl(baseUrl)
        .client(httpClient)
        .addConverterFactory(
            GsonConverterFactory.create(
                GsonBuilder().registerTypeAdapterFactory(
                    GsonTypeAdapterFactory()
                ).create()
            )
        ).build().create(serviceClass)


    private fun loggerInterceptor(): Interceptor {
        val loggingInterceptor = HttpLoggingInterceptor { message: String ->
            LogUtils.e(
                "http message:",
                "-------$message"
            )
        }
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        return loggingInterceptor
    }
}